// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const fs = require('fs')
const path = require('path')
const FormData = require('form-data');
let uniID=require('uni-id')
const db = uniCloud.database();
const nodemailer = require("nodemailer");
async function emainFormat({email='',subject='',text='',html,attachments=[]}){
	console.log(email,subject,text,html,attachments)
	let testAccount = await nodemailer.createTestAccount();
	let transporter = nodemailer.createTransport({
		 host: "smtp.qq.com",
		 port: 587,
		 secure: false, // true for 465, false for other ports
		 auth: {
		   user: "760995421@qq.com", // generated ethereal user
		   pass: "tsuivsfwawbubbhh", // generated ethereal password
		 },
	});
	let info = await transporter.sendMail({
		from: '"李敬辉 👻" 760995421@qq.com', // sender address
		to: email, // list of receivers
		subject: subject, // Subject line
		text: text, // plain text body
		// html: "你好吗? <img src='https://vkceyugu.cdn.bspapp.com/VKCEYUGU-62ec721a-a0ff-4726-a9f0-0e206b972095/3c2b3501-810b-485b-ad04-942f5515d8c3.jpg'></img>", // html body
	    html:html,
		// html:"Embedded image: <img src='cid:unique@nodemailer.com'/>",
		attachments:attachments
	});
	return info
}
module.exports = {
	_before: function () { // 通用预处理器
		const methodName = this.getMethodName()
		const clientInfo = this.getClientInfo()
		this.uniID = uniID.createInstance({ // 创建uni-id实例，其上方法同uniID
			clientInfo
		})
		console.log(methodName,clientInfo)
	},
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	
	async upload(param) {
		if (!param) {
			return {
				errCode: 'PARAM_IS_NULL',
				errMsg: '参数不能为空'
			}
		}
		const {filepath,type}=param
		// 将base64转为buffer
		const buffer=new Buffer(filepath,'base64') 
		// console.log(type,buffer,Buffer.isBuffer(buffer))
		//将json字符串读取到缓冲区
		// const buffer = Buffer.from(filepath);
		// console.log(filepath,buffer,filepath.data,Buffer.isBuffer(buffer))
		let form = new FormData()
		/* 
		// 对线上地址获取成buffer数据包
		const url = await uniCloud.httpclient.request('https://vkceyugu.cdn.bspapp.com/VKCEYUGU-a8a16cef-f2b9-4644-b216-3b95bcb12602/eed2e97a-be28-4e6d-beb3-ca338d195858.jpg')
		let buff = new Buffer(url.data);
		console.log(buff)
		*/
		/* 
		// 上传本地路径下的图片
		console.log(path.resolve(__dirname, './images/a.jpg'))
		form.append('media', fs.readFileSync(path.resolve(__dirname, './images/a.jpg')), { // 为方便演示此处直接使用云函数目录下的test.jpg文件
			filename: `${Date.now()}.jpg`,
			contentType: 'image/jpeg'
		});
		*/
	    form.append('media',buffer, { 
			filename: `${Date.now()}.${type}`,
			contentType: `image/${type}`
	    });
		// form.append('otherParam', 'otherParam content');
		let data= await db.collection('setconfig').get()
		// 上传到微信服务端
		// ?access_token=${data.data[0].accessToken}&type=image
		const apiUrl=`https://api.weixin.qq.com/cgi-bin/media/upload?access_token=${data.data[0].accessToken}&type=image`
		const res = await uniCloud.httpclient.request(apiUrl, {
		    method: 'POST',
			content: form.getBuffer(), // 请求内容
			headers: form.getHeaders(), // 请求头
			dataType: 'json' // 此处指定为json表示将此请求的返回值解析为json
		})
		console.log(res)
		if(res.data.type){
			// 将media_id添加到数据库中
			let res1=await db.collection('mini-media-demo').add({
				type:res.data.type,
				media_id:res.data.media_id,
				created_at:res.data.created_at*1000
			})
			console.log(res1)
			return {
				res1
			}
		}
		// 返回结果
		return {
			Error:'1',errMsg:'上传临时素材失败'
		}
	},
	// 获取小程序码
	async getminicode(){
		let data= await db.collection('setconfig').get()
		// 小程序必须上线才能获取到数据
		let url=`https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${data.data[0].accessToken}`
		const res = await uniCloud.httpclient.request(url, {
		    method: 'POST',
			data:{
				scene:'cloudtest',
				page:'pages/index/index',
				env_version:'develop',
			},
			contentType: 'json',
			dataType: 'json' // 此处指定为json表示将此请求的返回值解析为json
		})
		console.log(res)
		return res
	},
	async checkeText(param){
		const {content}=param
		const token = this.getUniIdToken()
		if(!token){
			return 'token不存在'
		}
		// console.log(token,methodName,clientInfo)
		let payload = await this.uniID.checkToken(token)
		const userinfor = await this.uniID.getUserInfo({
			 uid:payload.uid,
		});
		let data= await db.collection('setconfig').get() 
		let url=`https://api.weixin.qq.com/wxa/msg_sec_check?access_token=${data.data[0].accessToken}`
		const res = await uniCloud.httpclient.request(url, {
		    method: 'POST',
			data:{
				content:content,
				scene:2,
				version:2,
				openid:userinfor.userInfo.openid
			},
			contentType: 'json',
			dataType: 'json' // 此处指定为json表示将此请求的返回值解析为json
		})
		console.log(res)
		return res
	},
	async sendEmailCode(param){
		console.log(param)
		let reg = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/
		let {email}=param
		console.log(reg.test(email))
		if(!email||!reg.test(email)){
			return {
				errCode:-1,
				errMsg:'邮箱格式不正确', 
				success:false
			}
		}
		let type='login' // register
		const randomStr = '00000' + Math.floor(Math.random() * 1000000)
		const verifyCod = randomStr.substring(randomStr.length - 6)
		console.log(randomStr,verifyCod)
		// send mail with defined transport object
		let emailInfor={
			email:email,
			subject:'验证码',
			text:'',
			html:`你的验证码是： ${verifyCod} ,如非本人操作，请忽略！请勿回复此邮箱`,
			attachments: [
				{   // utf-8 string as an attachment
				   filename: 'love.txt',
				   content: '你傻啊!'
				},
				// {
				// 	filename: 'image.png',
				// 	path: path.resolve(__dirname, './images/a.jpg'),
				// 	cid: 'unique@nodemailer.com' //same cid value as in the html img src
				// }
			]
		}
		let info=await emainFormat(emailInfor)
		console.log(info)
		if(info.messageId){//发送成功，将验证码入库
			let data=await uniCloud.callFunction({
				name:'uni-id-cf',
				data:{
					action:'setCode',
					params:{
						email:email,
						code:verifyCod,
						type:type
					}
				},
			})
			console.log(data)	
			return data
		}
		return {
			errCode:-1,
			errMsg:'验证码发送失败', 
			success:false
		}
	},
	async test(){
		let url='https://v0.yiketianqi.com/api?unescape=1&version=v61&appid=27793545&appsecret=nvFQQ5jO'
		const res = await uniCloud.httpclient.request(url,{
			method:'GET',
			data:{
				city:'广州',
				province:'广东'
			},
			contentType: 'json', // 指定以application/json发送data内的数据
			dataType: 'json' 
		})
		console.log(res)
		if(res.status==200&&res.data){
			let data=res.data
			let emailInfor={
				email:'760995421@qq.com',
				subject:'天气预报',
				text:'',
				html:`
				<div>
				<p>
				你当前所在的城市${data.city}天气情况:<span style="color:red;">${data.wea}</span>,实时温度在${data.tem2}-${data.tem1}之间。空气等级:<span style="color:red;">${data.air_level},${data.air_tips}</span>。
				</p>
				<img src='https://vkceyugu.cdn.bspapp.com/VKCEYUGU-62ec721a-a0ff-4726-a9f0-0e206b972095/0f1998fa-901d-4681-9c02-6caf1083ba2c.jpg' style="width:660px;height:660px;border-radius:50%;"></img>
				</div>`,
			}
			let info=await emainFormat(emailInfor)
			if(info.messageId){
				return {
					errCode:0,
					errMsg:'发送成功', 
					success:true
				}
			}
		}
		return {
			errCode:-1,
			errMsg:'发送失败', 
			success:false
		}
	},
	_timing: async function () { 
		console.log('triggered by timing 天气邮件推送')
		let url='https://v0.yiketianqi.com/api?unescape=1&version=v61&appid=27793545&appsecret=nvFQQ5jO'
		const res1 = await uniCloud.httpclient.request(url,{
			method:'GET',
			data:{
				city:'广州',
				province:'广东'
			},
			contentType: 'json', // 指定以application/json发送data内的数据
			dataType: 'json' 
		})
		console.log(res1)
		if(res1.status==200&&res1.data){
			let data=res1.data
			let emailInfor={
				email:'760995421@qq.com',
				subject:'天气预报',
				text:'',
				html:`
				<div>
				<p>
				你当前所在的城市${data.city}天气情况:<span style="color:red;">${data.wea}</span>,实时温度在${data.tem2}-${data.tem1}之间。空气等级:<span style="color:red;">${data.air_level},${data.air_tips}</span>。
				</p>
				<img src='https://vkceyugu.cdn.bspapp.com/VKCEYUGU-62ec721a-a0ff-4726-a9f0-0e206b972095/0f1998fa-901d-4681-9c02-6caf1083ba2c.jpg' style="width:660px;height:660px;border-radius:50%;"></img>
				</div>`,
			}
			let info=await emainFormat(emailInfor)
			if(info.messageId){
				return {
					errCode:0,
					errMsg:'发送成功', 
					success:true
				}
			}
		}
		return {
			errCode:-1,
			errMsg:'发送失败', 
			success:false
		}
	}
}
